# File: app.py
from flask import Flask, request, render_template_string, redirect
import sqlite3
import os
import subprocess
import yaml
from base64 import b64decode
import pickle

app = Flask(__name__)

# Vulnerable database setup
def init_db():
    conn = sqlite3.connect('users.db')
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS users
                 (id INTEGER PRIMARY KEY, username TEXT, password TEXT)''')
    conn.commit()
    conn.close()

@app.route('/')
def home():
    # Vulnerable template injection
    name = request.args.get('name', '')
    template = '''
        <h1>Welcome to Vulnerable App</h1>
        Hello ''' + name + '''!
        <form action="/search" method="GET">
            <input type="text" name="query">
            <input type="submit" value="Search">
        </form>
    '''
    return render_template_string(template)

@app.route('/search')
def search():
    # Vulnerable OS command injection
    query = request.args.get('query', '')
    result = subprocess.check_output(f"find . -name '*{query}*'", shell=True)
    return result

@app.route('/config')
def config():
    # Vulnerable YAML deserialization
    config_data = request.args.get('data', '')
    if config_data:
        # Unsafe YAML loading
        return yaml.load(config_data)
    return "No config provided"

@app.route('/data')
def data():
    # Vulnerable pickle deserialization
    data = request.args.get('pickle', '')
    if data:
        # Unsafe pickle loading
        return pickle.loads(b64decode(data))
    return "No data provided"

@app.route('/login', methods=['POST'])
def login():
    # SQL Injection vulnerability
    username = request.form.get('username')
    password = request.form.get('password')
    
    conn = sqlite3.connect('users.db')
    c = conn.cursor()
    # Vulnerable SQL query
    query = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'"
    c.execute(query)
    user = c.fetchone()
    conn.close()
    
    if user:
        return "Login successful"
    return "Login failed"

if __name__ == '__main__':
    init_db()
    app.run(debug=True, host='0.0.0.0')


